package com.wgchao.authmanager.infrastructure.repository;

import com.wgchao.authmanager.domain.model.Handle;
import com.wgchao.authmanager.domain.repository.HandleRepository;
import com.wgchao.authmanager.infrastructure.exception.IdentifyUsedException;
import com.wgchao.authmanager.infrastructure.exception.ObjectNotExistException;
import com.wgchao.authmanager.infrastructure.jpa.entity.HandleInfo;
import com.wgchao.authmanager.infrastructure.jpa.repository.HandleInfoJpaRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName: HandleRepositoryImpl
 * @author: wgchao
 * @createTime: 2020/5/9 2:16 PM
 * @Description: TODO
 */
@Component
public class HandleRepositoryImpl implements HandleRepository {
    @Autowired
    private HandleInfoJpaRepository handleInfoJpaRepository;

    @Override
    public void add(Handle handle) {
        if(handle.findId().compareTo(-1L) == 0){
            HandleInfo handleInfo = handleInfoJpaRepository.findFirstByIdentify(handle.getIdentify());
            if(handleInfo != null){
                throw new IdentifyUsedException("标识已被使用");
            }
        }
        HandleInfo handleInfo = new HandleInfo();
        BeanUtils.copyProperties(handle, handleInfo);
        handleInfo.setId(handle.findId());
        handleInfo.setVersion(handle.findVersion());

        handleInfo = handleInfoJpaRepository.save(handleInfo);
    }

    @Override
    public void remove(Handle handle, String operator) {
        HandleInfo handleInfo = handleInfoJpaRepository.findFirstByIdentify(handle.getIdentify());
        if(handleInfo == null){
            throw new ObjectNotExistException("操作资源不存在");
        }
        handleInfoJpaRepository.delete(handleInfo);
    }

    @Override
    public Handle get(String id) {
        HandleInfo handleInfo = handleInfoJpaRepository.findFirstByIdentify(id);
        if(handleInfo == null){
            return null;
        }
        Handle handle = new Handle(handleInfo.getId(), handleInfo.getIdentify(),
                handleInfo.getName(), handleInfo.getRemark(), handleInfo.getVersion());
        return handle;
    }
}
